package tools;

import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Properties;

/**
 * @author :chensi
 */
public class ZookeeperClient {
    public ZooKeeper getZk(String host,int timeOut) {
        ZooKeeper zk = null;
        try {
            zk = new ZooKeeper(host, timeOut,null);
        } catch (Exception e){
            e.printStackTrace();
        }
        return zk;
    }

    public Properties getAll(ZooKeeper zk,String path) {
        Properties prop = new Properties();
        if (zk != null) {
            // val prop = new Properties()
            try {
                Stat stat = zk.exists(path, false);
                if (stat != null) {
                    List<String> childrenList = zk.getChildren(path, false);
                    for (String child : childrenList) {
                        String childPath = path;
                        if (!childPath.endsWith("/")) {
                            childPath = childPath + "/";
                        }
                        childPath = childPath + child;
                        byte[] buffer = zk.getData(childPath, true, stat);
                        if (buffer != null) {
                            String value = new String(buffer, StandardCharsets.UTF_8);
                            if (value != null) {
                                prop.setProperty(child.toString().trim(), value.trim());
                            }
                            System.out.println("("+child+ ": "+ prop.get(child)+")");
                        }
                    }
                }
            } catch (Exception e){
                e.printStackTrace();
            }
        }
        return prop;
    }
}
